<template>
  <el-dialog v-model="visible" title="选择供应商" width="50%" draggable>
    <div class="search-bar">
      <el-select v-model="currentCategory" placeholder="类别" style="width: 150px">
        <el-option value="" label="全部类别" />
        <el-option v-for="category in allCategories" :key="category" :label="category" :value="category" />
      </el-select>

      <el-input v-model="searchKeyword" placeholder="输入编号/名称/联系人/电话查询" style="width: 300px; margin-left: 10px" />
      <el-button type="primary" @click="handleSearch" style="margin-left: 10px">
        查询
      </el-button>
    </div>

    <el-table :data="filteredSuppliers" style="width: 100%" border highlight-current-row @row-click="handleRowClick"
      :header-cell-style="{ 'background-color': '#f5f7fa' }" v-loading="loading">
      <el-table-column prop="SupplierType" label="类别" width="120" />
      <el-table-column prop="SupplierCode" label="编号" width="120" sortable />
      <el-table-column prop="SupplierName" label="名称" width="180" sortable />
      <el-table-column prop="SupplierConcat" label="联系人" width="120" />
      <el-table-column prop="SupplierPhone" label="联系电话" width="150" />
    </el-table>

    <div class="pagination" v-if="total > 0">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
        :total="total" layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button @click="handleEmptySelection">
        空选
      </el-button>
      <el-button type="primary" @click="confirmSelection" :disabled="!selectedSupplier">
        选择供应商
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, defineEmits, defineExpose } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";

const emit = defineEmits(["confirm"]);

// 状态管理
const visible = ref(false);
const currentCategory = ref("");
const searchKeyword = ref("");
const selectedSupplier = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 供应商数据
const supplierList = ref([]);
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 获取供应商数据
const getSupplierList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize
    };
    const res = await axios.get('/api/basic/supplier/supplierByPage', { params });

    if (res.data.code == 5200) {
      console.log('获取数据库供应商', res)
      const supplierData = res.data.pageInfo?.list || [];

      // 转换数据格式
      supplierList.value = supplierData.map(item => ({
        SupplierId: item.id ||'',
        SupplierName: item.name || '',
        SupplierCode: item.code || '',
        SupplierType: getCategoryText(item.category),
        SupplierConcat: item.primaryContactName || '',
        SupplierPhone: item.primaryContactPhone || '',
        supplierAddress: item.primaryContactAddress || '',
        // 保留原始数据，便于后续使用
        rawData: item
      }));

      pageInfo.total = res.data.pageInfo.total || 0;
    } else {
      ElMessage.error(res.data.msg || '获取供应商数据失败');
    }
  } catch (error) {
    console.error('获取供应商数据失败:', error);
    ElMessage.error('获取供应商数据失败');
  } finally {
    loading.value = false;
  }
};

// 类别转换函数
const getCategoryText = (category) => {
  const categoryMap = {
    1: '原材料供应商',
    2: '成品供应商',
    3: '技术服务商',
    4: '物流供应商'
  };
  return categoryMap[category] || `类别${category}`;
};

// 获取所有类别
const allCategories = computed(() => {
  const categories = new Set();
  supplierList.value.forEach((supplier) => {
    if (supplier.SupplierType) categories.add(supplier.SupplierType);
  });
  return Array.from(categories);
});

// 过滤后的供应商列表
const filteredSuppliers = computed(() => {
  let result = [...supplierList.value];

  // 类别过滤
  if (currentCategory.value) {
    result = result.filter((s) => s.SupplierType === currentCategory.value);
  }

  // 关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(
      (s) =>
        (s.SupplierCode && s.SupplierCode.toLowerCase().includes(keyword)) ||
        (s.SupplierName && s.SupplierName.toLowerCase().includes(keyword)) ||
        (s.SupplierConcat && s.SupplierConcat.toLowerCase().includes(keyword)) ||
        (s.SupplierPhone && s.SupplierPhone.includes(keyword))
    );
  }

  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  return result.slice(start, start + pageSize.value);
});

// 总记录数
const total = computed(() => {
  let result = [...supplierList.value];

  if (currentCategory.value) {
    result = result.filter((s) => s.SupplierType === currentCategory.value);
  }

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    result = result.filter(
      (s) =>
        (s.SupplierCode && s.SupplierCode.toLowerCase().includes(keyword)) ||
        (s.SupplierName && s.SupplierName.toLowerCase().includes(keyword)) ||
        (s.SupplierConcat && s.SupplierConcat.toLowerCase().includes(keyword)) ||
        (s.SupplierPhone && s.SupplierPhone.includes(keyword))
    );
  }

  return result.length;
});

// 行点击处理
const handleRowClick = (row) => {
  selectedSupplier.value = row;
};

// 确认选择
const confirmSelection = () => {
  if (selectedSupplier.value) {
    emit("confirm", selectedSupplier.value);
    visible.value = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  currentCategory.value = "";
  searchKeyword.value = "";
  selectedSupplier.value = null;
  currentPage.value = 1;
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
};

// 打开对话框
const open = () => {
  visible.value = true;
  resetFilters();
  // 每次打开时重新获取数据，确保数据最新
  getSupplierList();
};

// 刷新数据方法，可供父组件调用
const refreshData = () => {
  getSupplierList();
};

defineExpose({ open, refreshData });

// 简化空选方法
// 简化空选方法 - 返回空字符串
const handleEmptySelection = () => {
  // 创建包含空字符串的空供应商对象
  const emptySupplier = {
    SupplierName: '',
    SupplierCode: '',
    SupplierType: '',
    SupplierConcat: '',
    SupplierPhone: '',
    supplierAddress: '',
    rawData: null
  };

  selectedSupplier.value = emptySupplier;
  emit("confirm", emptySupplier);
  visible.value = false;
  ElMessage.success('已选择空选');
};
</script>

<style scoped>
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.pagination {
  margin-top: 15px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table .el-table__header th) {
  background-color: #f5f7fa !important;
}

:deep(.el-table__row.current-row) {
  background-color: #f0f7ff;
}
</style>